package com.breeze.toolkit.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;

import com.breeze.toolkit.util.DialogUtil;
import com.breeze.toolkit.util.ToastUtil;

import retrofit.Call;

/**
 * Created by john on 2016/8/23.
 */
public class LoadingController implements Dialog.OnCancelListener {
	private String mLoadingMsg;
	private String mToastMsg;
	private Context mContext;
	private Dialog mDialog;
	private boolean mIsShowLoading = true;
	private boolean mIsCloseLoadingWhenFinished = true;
	private boolean mIsShowToastWhenFailed = true;
	private boolean mIsCanceled = false;
	private Call mCallDelegate;

	public LoadingController(Context context, boolean closeLoadingWhenFinished) {
		this(context, true, closeLoadingWhenFinished, true, null);
	}

	public LoadingController(Context context, String loadingMsg) {
		this(context, true, true, true, loadingMsg);
	}

	public LoadingController(Context context, boolean showLoading, boolean closeLoadingWhenFinished, boolean showToastWhenFailed, String loadingMsg) {
		this.mContext = context;
		this.mIsShowLoading = showLoading;
		this.mIsCloseLoadingWhenFinished = closeLoadingWhenFinished;
		this.mIsShowToastWhenFailed = showToastWhenFailed;
		this.mLoadingMsg = loadingMsg;
	}

	public void setToastMsg(String toastMsg) {
		this.mToastMsg = toastMsg;
	}

	public void setCallDelegate(Call delegate) {
		this.mCallDelegate = delegate;
	}

	public void setToastMsgId(int strId) {
		this.mToastMsg = mContext.getResources().getString(strId);
	}

	public boolean isCanceled() {
		return mIsCanceled;
	}

	/**
	 * 监听加载框取消事件，在加载框关闭时取消请求
	 * @param dialog : 加载框
	 */
	@Override
	public void onCancel(DialogInterface dialog) {
		mIsCanceled = true;
		if (mCallDelegate != null) {
			mCallDelegate.cancel();
		}
	}

	public void start() {
		if (mIsShowLoading) {
			if (TextUtils.isEmpty(mLoadingMsg)) {
				mDialog = DialogUtil.showLoadingDialog(mContext);
			} else {
				mDialog = DialogUtil.showLoadingDialog(mContext, mLoadingMsg);
			}

			if (mDialog != null) {
				mDialog.setOnCancelListener(this);
			}
		}
	}


	/**
	 * 用于请求失败时处理，关闭加载框并提示失败信息
	 */
	public void stop() {
		close();

		if (mIsShowToastWhenFailed && !TextUtils.isEmpty(mToastMsg)) {
			ToastUtil.show(mContext, mToastMsg);
		}
	}

	/**
	 * 用于请求成功时处理，仅关闭加载框
	 */
	public void close() {
		if (mIsCloseLoadingWhenFinished) {
			DialogUtil.dismissLoadingDialog(mDialog);
		}
	}
}
